package com.cloudcc.mobile.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.OnClick;

import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.util.DialogUtils.OnDoClickListener;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.web.IWebView;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase.OnRefreshListener;
import com.cloudcc.mobile.weight.ui.PullToRefreshWebView;

/**
 * 加载的webview
 * 
 * @author Administrator
 * 
 */
public class MyWebActivity extends BaseActivity implements IWebView {
	public static final String ARG_PLANET_NUMBER = "planet_number";

	@Bind(R.id.myname)
	TextView name;
	@Bind(R.id.netcheck)
	LinearLayout netcheck;
	@Bind(R.id.fanhuibtn)
	ImageView fanhuibtn;
	@Bind(R.id.myweb)
	PullToRefreshWebView weixinview;
	@Bind(R.id.caozuo) RelativeLayout caozuo;
	@Bind(R.id.myshuaxin) ImageView shuaxin;

	public WebView weixin;
	private CustomProgressDialog progressDialog;
	private NetWork net;
	private String urlString;
	private ValueCallback<Uri> mUploadMessage;
	private final int PINK_RESULT = 2;

	private float dx;
	private float ux;

	private String mUrl = StringUtils.EMPTY;
	private String mTitle = StringUtils.EMPTY;

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);

		mUrl = getIntent().getStringExtra(KEY_URL);
		mTitle = getIntent().getStringExtra(KEY_NAME);
		setView();
		addListener();
	}

	@Override
	public int getLayoutId() {
		return R.layout.myweb;
	}

	private void setView() {
		weixin = weixinview.getRefreshableView();
		name.setText(mTitle.length() > 12 ? mTitle.substring(0, 12) : mTitle);
		caozuo.setVisibility(View.GONE);
		progressDialog = CustomProgressDialog.createDialog(mContext);
		webview();
	}

	/**
	 * webview操作类
	 */
	public void webview() {
		AppContext.isFirst = true;
		AppContext.isError = false;
		weixin.requestFocus();
		weixin.loadUrl(mUrl);
		weixin.reload();
		WebSettings webstting = weixin.getSettings();
		webstting.setJavaScriptEnabled(true);
		// 设置可以访问文件
		webstting.setAllowFileAccess(true);
		webstting.setSupportZoom(true);
		// 设置支持缩放
		webstting.setBuiltInZoomControls(true); // 缩放
		webstting.setJavaScriptCanOpenWindowsAutomatically(true);
		weixin.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				startProgressDialog();
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// 加载完了再调用js登录代码
				stopProgressDialog();
				if (AppContext.isError) {
					weixin.setVisibility(View.GONE);
					caozuo.setVisibility(View.GONE);
					netcheck.setVisibility(View.VISIBLE);
					if (!AppContext.isFirst) {
						AppContext.isError = false;
					}
					AppContext.isFirst = false;
				} else {
					weixin.setVisibility(View.VISIBLE);
					caozuo.setVisibility(View.GONE);
					netcheck.setVisibility(View.GONE);
					AppContext.isFirst = true;
					AppContext.isError = false;
				}
				super.onPageFinished(view, url);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				return true;
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				AppContext.isError = true;
				super.onReceivedError(view, errorCode, description, failingUrl);
			}
		});
		weixin.setWebChromeClient(new WebChromeClient() {
			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				return true;
			}

			@Override
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {
				DialogUtils dialogutils = new DialogUtils(mContext);
				dialogutils.showUpdateDialog(mContext, "网页提示", message);
				dialogutils.setOnDoClicktListener(new OnDoClickListener() {
					@Override
					public void confirm() {
						result.confirm();
					}

					@Override
					public void cancel() {
						result.cancel();
					}
				});
				return true;
			}

			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String acceptType) {
				if (mUploadMessage != null)
					return;
				mUploadMessage = uploadMsg;
				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
				i.addCategory(Intent.CATEGORY_OPENABLE);
				i.setType("*/*");
				startActivityForResult(Intent.createChooser(i, "选择文件"),
						PINK_RESULT);
			}

			// For Android > 4.1.1
			@SuppressWarnings("unused")
			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String acceptType, String capture) {
				openFileChooser(uploadMsg, acceptType);
			}

			// For Android < 3.0
			@SuppressWarnings("unused")
			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				openFileChooser(uploadMsg, "");
			}
		});
	}

	@SuppressLint("SdCardPath")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == PINK_RESULT) {
			if (null == mUploadMessage)
				return;
			Uri result = intent == null || resultCode != RESULT_OK ? null
					: intent.getData();
			mUploadMessage.onReceiveValue(result);
			mUploadMessage = null;
		}
	}

	/**
	 * dialog开始显示
	 */
	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(mContext);
			progressDialog.setCancelable(true);
			progressDialog.setCanceledOnTouchOutside(false);
			// progressDialog.setMessage("正在加载中...");
		}
		progressDialog.show();
	}

	/**
	 * 停止dialog
	 */
	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	@OnClick(R.id.back)
	public void back() {
		this.finish();
	}

	/**
	 * 监听 mWebView.goBack(); //后退 mWebView.goForward();//前进 mWebView.reload();
	 * //刷新
	 */
	private void addListener() {
		/**
		 * 下拉刷新webview
		 */
		weixinview.setOnRefreshListener(new OnRefreshListener<WebView>() {
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<WebView> refreshView) {
				weixin.reload();
				weixinview.onPullDownRefreshComplete();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<WebView> refreshView) {
			}
		});
		netcheck.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				weixin.reload(); // 刷新
				AppContext.isFirst = true;
				AppContext.isError = false;
			}
		});
		fanhuibtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (StringUtils.equals(urlString, mUrl)) {
					weixin.reload(); // 刷新
				} else {
					weixin.goBack(); // 后退
				}
			}
		});
		shuaxin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				weixin.reload(); // 刷新
			}
		});
	}

	@Override
	protected void onDestroy() {
		weixin.clearCache(true);
		super.onDestroy();
	}

	/**
	 * 滑动返回
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// 当按下时处理
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			dx = ev.getX();
		} else if (ev.getAction() == MotionEvent.ACTION_UP) {// 松开处理
			ux = ev.getX();
			if ((int) (ux - dx) > DensityUtils.getScreenWidth(mContext) / 2
					&& ux > dx) {
				finish();
				// 设置切换动画，从右边进入，左边退出
				overridePendingTransition(R.anim.in_from_left,
						R.anim.out_to_right);
			}
		}
		return super.dispatchTouchEvent(ev);
	}
}